#include <stdio.h>
#include <stdlib.h>

#include "../../include/list.h"


static void print_list(const list_t *list)
{
	unsigned int idx = 0;
	list_node_t *n;
	
	if (!list){
		fprintf(stderr, "list is null!\n");
		return;
	}

	fprintf(stdout, "list size is %d\n", list_size(list));
	n = list_head(list);
	
	while(1)
	{
		fprintf(stdout, "list[%03d] = %03d\n", idx, *(int *)list_data(n));
		idx++;

		if (list_is_tail(list, n))
			break;
		else
			n = list_next(n);
	}

	return;
}

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[])
{
	list_t list;
	list_node_t	*n;
	unsigned int idx;
	int *data;
	int ret;

	list_init(&list, free);
	for (idx = 10; idx > 0; idx--)
	{
		if (!(data = (int *)malloc(sizeof(int)))){
			fprintf(stdout, "data malloc failed\n");
			return -1;
		}

		*data = idx;

		if (list_insert_next(&list, NULL, data)){
			fprintf(stdout, "data insert failed\n");
			return -1;
		}
	}
	print_list(&list);

	n = list_head(&list);
	for (idx = 0; idx < 7; idx++)
	{
		n = list_next(n);
	}
	
	fprintf(stdout, "ready to remove after list[%03d] = %03d\n", 
			idx, *(int *)list_data(n));

	ret = list_remove_next(&list, n, (void **)&data);
	if (ret)
		return -1;
	print_list(&list);

	*data = 11;
	fprintf(stdout, "insert after tail %d\n", *data);
	ret = list_insert_next(&list, list_tail(&list), (void *)data);
	if (ret)
		return -1;
	print_list(&list);

	fprintf(stdout, "remove after head\n");
	ret = list_remove_next(&list, list_head(&list), (void **)&data);
	if (ret)
		return -1;
	print_list(&list);

	fprintf(stdout, "insert 12 after head\n");
	*data = 12;
	ret = list_insert_next(&list, list_head(&list), (void *)data);
	print_list(&list);

	ret = list_is_head(&list, list_head(&list));
	fprintf(stdout, "testing list_is_head...result = %d\n", ret);

	ret = list_is_tail(&list, list_tail(&list));
	fprintf(stdout, "testing list_is_tail...result = %d\n", ret);
	
	ret = list_is_head(&list, list_tail(&list));
	fprintf(stdout, "testing list_is_head...result = %d\n", ret);
	
	ret = list_is_tail(&list, list_head(&list));
	fprintf(stdout, "testing list_is_tail...result = %d\n", ret);
	
	list_destroy(&list);

	return 0;
}
